package com.app.base.service.core.personnel.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.app.base.config.exception.SaaSException;
import com.app.base.service.auth.service.SysUserService;
import com.app.base.service.core.personnel.entity.PersonDel;
import com.app.base.service.core.personnel.entity.PersonInfo;
import com.app.base.service.core.personnel.entity.PersonReview;
import com.app.base.service.core.personnel.entity.WorkExperience;
import com.app.base.service.core.personnel.mapper.PersonInfoMapper;
import com.app.base.service.core.personnel.service.PersonDelService;
import com.app.base.service.core.personnel.service.PersonInfoService;
import com.app.base.service.core.personnel.service.PersonReviewService;
import com.app.base.service.core.personnel.service.WorkExperienceService;
import com.app.base.utlis.data.PersonInfoUtils;
import com.app.base.utlis.email.EmailUtils;
import com.app.base.utlis.email.Mail;
import com.app.base.utlis.result.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class PersonInfoServiceImpl extends ServiceImpl<PersonInfoMapper, PersonInfo> implements PersonInfoService {

    @Resource
    private SysUserService userService;

    @Resource
    private WorkExperienceService workExperienceService;

    @Resource
    private PersonDelService personDelService;

    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private PersonReviewService reviewService;

    @Override
    public Result saveOrUpdatePersonInfo(String userId, PersonInfo personInfo) {
        String companyId = userService.getCompanyId(userId);
        try{

            if (StringUtils.isEmpty(personInfo)) {
                throw new SaaSException("人才信息为空");
            }
            personInfo.setModifyBy(userId);

            if (StringUtils.isEmpty(personInfo.getId())){
                personInfo.setReviewStatus(0);
                personInfo.setStatus(0);
                personInfo.setCreatedBy(userId);
                personInfo.setCompanyId(companyId);
                baseMapper.insert(personInfo);
                personInfo.getWorks().forEach(work->{
                    work.setCreatedBy(userId);
                    work.setModifyBy(userId);
                    work.setPersonId(personInfo.getId());
                    workExperienceService.save(work);
                });
            }else {
                baseMapper.updateById(personInfo);
                personInfo.getWorks().forEach(work -> {
                    work.setModifyBy(userId);
                    if (StringUtils.isEmpty(work.getId())) {
                        work.setCreatedBy(userId);
                        work.setPersonId(personInfo.getId());
                        workExperienceService.save(work);
                    }else {
                        workExperienceService.updateById(work);
                    }
                });
            }

           return Result.ok();
       }catch(Exception e){
           log.error(e.getMessage());
           return Result.error(e.getMessage());
       }
    }

    @Override
    public Result pagePersonInfo(Long current, Long pageSize, String startTime, String endTime, String name, Integer education, String expectedPosition, String reviewer, String graduationSchool) {
        try{
            Page<PersonInfo> page = new Page<>(current,pageSize);
            List<PersonInfo> personList = baseMapper.pagePersonInfo(startTime,endTime,name,education,expectedPosition,reviewer,graduationSchool,page);
            page.setRecords(personList);

            return Result.ok(page);
        }catch(Exception e){
            log.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    @Override
    public Result deletePerson(String userId, String description, String id) {
        try{
            Result result = getPersonInfoById(id);
            PersonInfo data = (PersonInfo) result.getData().get("data");
            String json = JSONObject.toJSONString(data);

            PersonDel person = new PersonDel();
            person.setPersonInfo(json);
            person.setCreatedBy(userId);
            person.setModifyBy(userId);
            person.setDescription(description);
            personDelService.save(person);

            baseMapper.deleteById(id);

            return Result.ok();
        }catch(Exception e){
            log.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    @Override
    public Result emailNotice(String content, String id) {
        try{
            if (StringUtils.isEmpty(content)){
                throw new SaaSException("填写信息为空");
            }
            PersonInfo personInfo = baseMapper.selectById(id);
            Mail mail = new Mail();
            String email = personInfo.getEmail();
            mail.setSubject(personInfo.getName()+":面试通知");
            mail.setTo(email);
            mail.setText(content);
            mail.setSentDate(new Date());
            SimpleMailMessage simpleMailMessage = EmailUtils.simpleSend(mail);
            javaMailSender.send(simpleMailMessage);
            return Result.ok();

        }catch(Exception e){
            log.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    @Transactional
    @Override
    public Result passTheInterview(JSONObject json, String id, String userId) {
        try{
            String content = json.getString("content");
            if (StringUtils.isEmpty(content)) {
                throw new SaaSException("确认信息备注填写为空");
            }
            Integer status = json.getInteger("status");
            PersonReview review = new PersonReview();
            review.setStatus(status);
            review.setInfoId(id);
            review.setDescription(content);
            review.setCreatedBy(userId);
            review.setModifyBy(userId);
            reviewService.save(review);


            PersonInfo personInfo = baseMapper.selectById(id);
            personInfo.setReviewStatus(status);
            if (status == 3) {
                personInfo.setReviewDate(new Date());
            }
            baseMapper.updateById(personInfo);

            return Result.ok();
        }catch(Exception e){
            log.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    @Override
    public Result pagePersonAdopt(Long current, Long pageSize) {
        try{
            Page<PersonInfo> page = new Page<>(current,pageSize);
            List<PersonInfo> personInfos = baseMapper.pagePersonAdopt(page);
            page.setRecords(personInfos);
            return Result.ok(page);
        }catch(Exception e){
            log.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    @Override
    public Result getPersonInfoById(String id) {
        try{

            PersonInfo personInfo = baseMapper.selectById(id);

            personInfo.setPoliticCountenanceStr( PersonInfoUtils.getCountenance(personInfo));
            personInfo.setEducationStr( PersonInfoUtils.getEducations(personInfo));

            List<WorkExperience> experienceList = workExperienceService.list(
                    new LambdaQueryWrapper<WorkExperience>()
                            .eq(WorkExperience::getPersonId, id));

            personInfo.setWorks(experienceList);

            return Result.ok(personInfo);
        }catch(Exception e){
            log.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }
}
